package com.example.cloud.controller.finance;

import com.example.cloud.constants.CommonConstants;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.finance.PrintConfig;
import com.example.cloud.service.finance.PrintConfigService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import com.example.cloud.utils.ResultUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;


@RestController
@RequestMapping("/finance/print")
public class PrintConfigController {

    private static final Logger logger = Logger.getLogger(PrintConfigController.class);

    @Autowired
    private PrintConfigService printConfigService;

    @GetMapping("/getDefault/{hostName}")
    public Result getDefault(@PathVariable String hostName) {
        PrintConfig defaultPrint = new PrintConfig();
        try {
            defaultPrint = printConfigService.findOne(RequestUtil.getLoginUser().getAccountId(), hostName);
            if (defaultPrint == null) {
                return ResultUtil.fail("没有配置默认打印机");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultUtil.fail("系统异常,请联系管理员");
        }
        return ResultUtil.success(defaultPrint);
    }

    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody PrintConfig config) {
        try {
            config.setAccountId(RequestUtil.getLoginUser().getAccountId());
            BusinessUtil.appendRecord(config);
            config = printConfigService.saveOrUpdate(config);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultUtil.fail("系统异常,请联系管理员");
        }
        return ResultUtil.success(config);
    }

    @GetMapping("/checkPrintConfig")
    public Result checkPrintConfig() {
        Result result = new Result();
        result.setCode(CommonConstants.SUCCESS);
        try {
            // 机器唯一码
            String code = InetAddress.getLocalHost().getHostName();
            PrintConfig defaultConfig = printConfigService.findOne(RequestUtil.getLoginUser().getAccountId(), code);
            if (defaultConfig == null) {
                result.setCode(-2);// 没有配置默认打印机
            } else {
                result.setData(defaultConfig.getPrintName());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultUtil.fail("系统异常,请联系管理员");
        }
        return result;
    }
}

